﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.SiteDefinition.Core;
using Microsoft.SharePoint.Utilities;

namespace Kiiro.SiteDefinition.ControlTemplates
{
    [ViewStateModeById]
    public partial class TeamMemberCollection : System.Web.UI.UserControl
    {
        public BasePage Base
        {
            get { return ( BasePage ) Page; }
        }

        List<User> users = new List<User> ( );
        public List<User> Users
        {
            get { return users; }
            set { users = value; }
        }

        List<TeamMember> teamMembers = new List<TeamMember> ( );
        public List<TeamMember> TeamMembers
        {
            get { return teamMembers; }
            set { teamMembers = value; }
        }

        List<int> selectedIds = new List<int> ( );
        public List<int> SelectedIds
        {
            get { return selectedIds; }
            set { selectedIds = value; }
        }

        public bool ReadOnly
        {
            get { return ViewState [ "ReadOnly" ] == null ? true : ( bool ) ViewState [ "ReadOnly" ]; }
            set { ViewState [ "ReadOnly" ] = value; }
        }

        public PageMode PageMode
        {
            get { return ViewState [ "PageMode" ] == null ? PageMode.New : ( PageMode ) ViewState [ "PageMode" ]; }
            set { ViewState [ "PageMode" ] = value; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            if ( !IsPostBack )
            {
                if ( TeamMembers != null && TeamMembers.Count > 0 )
                    foreach ( TeamMember member in TeamMembers )
                        if ( member.User != null )
                            Users.Add ( member.User );

                if ( PageMode == PageMode.Display )
                {
                    PopulateDisplayMode ( );
                }
                else
                {
                    PopulateNewEditMode ( );
                }
            }
        }

        private void PopulateDisplayMode ( )
        {
            User user = null;
            HyperLink control = null;

            foreach ( int selectedId in SelectedIds )
            {
                user = Users.Find ( x => x.Id == selectedId );
                if ( user != null )
                {
                    control = new HyperLink ( );
                    Controls.Add ( control );
                    control.NavigateUrl = string.Format ( "{0}{1}?id={2}", Base.ServerRelativeUrl, Constants.PortalFileUrls.UserDisplay, user.SPUserId );
                    control.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( user.FullName );
                }
            }

            if (selectedIds.Count <= 0)
                Controls.Add(new LiteralControl("Not yet assigned."));
        }

        private void PopulateNewEditMode ( )
        {
            CheckBox control = null;

            if ( !ReadOnly )
            {
                control = new CheckBox ( );
                Controls.Add ( control );
                control.ID = "jq_select-all";
                control.CssClass = "jq_select-all";
            }

            foreach ( User user in Users )
            {
                if ( ( Page is ProjectPages.NewIssue
                    || Page is ProjectPages.EditIssue
                    || Page is ProjectPages.NewTask
                    || Page is ProjectPages.EditTask
                    || Page is ProjectPages.DisplayIssue
                    || Page is ProjectPages.DisplayTask )
                    || ( user.ReceiveEmailNotification && ( Page is ProjectPages.NewDiscussion || Page is ProjectPages.Upload ) )
                    )
                {
                    //check if member is a project manager
                    TeamMember member = teamMembers.Find(m => m.UserId == user.Id);
                    
                    control = new CheckBox ( );
                    Controls.Add ( control );
                    if ( member != null )
                        control.ID = string.Format ( "CONTROL_{0}_{1}_{2}_{3}", user.Id, SPHelpers.ConvertHtmlToKiiroSafeText ( user.FullName ), user.Email, member.IsProjectManager.ToString ( ) );
                    else
                        control.ID = string.Format ( "CONTROL_{0}_{1}_{2}", user.Id, SPHelpers.ConvertHtmlToKiiroSafeText ( user.FullName ), user.Email );
                    control.Checked = SelectedIds.Contains ( user.Id );
                    control.Enabled = !ReadOnly;
                }
            }
        }

        protected override void LoadViewState ( object savedState )
        {
            object [ ] viewState = savedState as object [ ];

            foreach ( string id in viewState [ 0 ] as string [ ] )
            {
                CheckBox control = new CheckBox ( );
                Controls.Add ( control );
                control.ID = id;
            }

            base.LoadViewState ( viewState [ 1 ] );
        }

        protected override object SaveViewState ( )
        {
            object [ ] viewState = new object [ 2 ];

            List<string> ids = new List<string> ( );
            foreach ( Control control in Controls )
            {
                ids.Add ( control.ID );
            }

            viewState [ 0 ] = ids.ToArray ( );
            viewState [ 1 ] = base.SaveViewState ( );

            return viewState;
        }

        protected override void Render ( HtmlTextWriter writer )
        {
            if ( Controls != null && Controls.Count > 0 )
            {
                if ( PageMode == PageMode.Display )
                {
                    bool first = true;
                    foreach ( Control control in Controls )
                    {
                        if ( !first )
                            writer.Write ( ", " );

                        control.RenderControl ( writer );

                        first = false;
                    }
                }
                else
                {
                    writer.Write ( "<ul id='team-member-collection'>" );

                    bool first = !ReadOnly;
                    if ( Controls.Count > 1 )
                    {
                        foreach ( Control control in Controls )
                        {
                            string[] strings = control.ID.Split ( new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries );
                            string labelText = strings.Length > 2 ? strings[2] : "All";

                            writer.Write ( string.Format ( "<li class='{0}'>", first ? "jq_select-all" : "" ) );
                            control.RenderControl ( writer );
                            writer.Write ( string.Format ( "<label>{0}</label></li>", labelText ) );

                            first = false;
                        }
                    }
                    else
                    {
                        string messageText = "No team members have the email notifications turned on.";
                        writer.Write ( string.Format ( "<label>{0}</label></li>", messageText ) );
                    }

                    writer.Write ( "</ul>" );
                }
            }
        }

        public List<int> GetSelectedIds ( )
        {
            List<int> selectedIds = new List<int> ( );
            foreach ( Control control in Controls )
            {
                CheckBox chkCheckBox = ( CheckBox ) control;
                if ( chkCheckBox != null && chkCheckBox.Checked && chkCheckBox.CssClass != "jq_select-all" )
                {
                    string [ ] strings = chkCheckBox.ID.Split ( new char [ ] { '_' }, StringSplitOptions.RemoveEmptyEntries );
                    if ( strings.Length > 1 )
                    {
                        int memberId = int.Parse ( strings [ 1 ].ToString ( ) );
                        selectedIds.Add ( memberId );
                    }
                }
            }
            return selectedIds;
        }

        public List<string> GetSelectedEmails ( )
        {
            List<string> emails = new List<string> ( );
            foreach ( Control control in Controls )
            {
                CheckBox chkCheckBox = ( CheckBox ) control;
                if ( chkCheckBox != null && chkCheckBox.Checked && chkCheckBox.CssClass != "jq_select-all" )
                {
                    string [ ] strings = chkCheckBox.ID.Split ( new char [ ] { '_' }, StringSplitOptions.RemoveEmptyEntries );
                    if ( strings.Length > 3 )
                    {
                        emails.Add ( strings [ 3 ].ToString ( ) );
                    }
                }
            }
            return emails;
        }

        public List<string> GetSelectedMembersEmails()
        {
            List<string> emails = new List<string>();
            foreach (Control control in Controls)
            {
                CheckBox chkCheckBox = (CheckBox)control;
                if (chkCheckBox != null && chkCheckBox.Checked && chkCheckBox.CssClass != "jq_select-all")
                {
                    string[] strings = chkCheckBox.ID.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                    if (strings.Length > 4)
                    {
                        if (strings[4] == "False")
                            emails.Add(strings[3].ToString());
                    }
                }
            }
            return emails;
        }

        public List<string> GetSelectedProjectManagersEmails()
        {
            List<string> emails = new List<string>();
            foreach (Control control in Controls)
            {
                CheckBox chkCheckBox = (CheckBox)control;
                // get all project managers emails even if not selected
                if (chkCheckBox != null && chkCheckBox.CssClass != "jq_select-all")
                {
                    string[] strings = chkCheckBox.ID.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
                    if (strings.Length > 4)
                    {
                        if (strings[4] == "True")
                            emails.Add(strings[3].ToString());
                    }
                }
            }
            return emails;
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/CONTROLTEMPLATES/Kiiro/TeamMemberCollection.ascx.cs $
 * 
 * 8     10/26/09 9:25a Adamw
 * 
 * 7     10/23/09 6:00p Adamw
 * Case 348
 * 
 * 6     30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 5     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/